<template>
  <div class="school-detail">
    <!--基本信息-->
    <school-basic-info
      :url="url"
      :selectEnums="selectArr"
      :basicInfo="basicInfo"
      @refreshData="getSchoolDetails"
      :schoolId="schoolId"
    ></school-basic-info>
    <!--校长信息-->
    <master-basic-info
      :url="url"
      :masterInfo="basicInfo.master || {}"
      :masterId="basicInfo.schoolHeadId"
      :selectEnums="selectArr"
      @refreshData="getSchoolDetails"
      :schoolId="schoolId"
      :gradeList="gradeList"
    ></master-basic-info>
    <!--教师信息-->
    <div class="m-h3-btn-box border margin-top30">
      <h3>教师信息</h3>
      <div class="u-btn-box">
        <a
          class="button_txt"
          :href="
            'https://jzjx-prod-resource.oss-cn-hangzhou.aliyuncs.com/common/export/teacher.xlsx?time=' +
              new Date().getTime()
          "
          download="老师导入模板"
          ><el-button type="primary" size="small">下载模板</el-button></a
        >
        <div class="margin-left10 margin-right10">
          <!-- <el-upload
            ref="uploadExl"
            action
            multiple
            :limit="1"
            :http-request="importObj"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :file-list="teaterFileList"
          >

          </el-upload> -->
          <el-button type="primary" class="u-btn" size="small"
            >批量导入<updateFile
              updata-id="inputName11"
              accpetObj="xls,xlsx,"
              @updata="file => importObj(file[0].files)"
          /></el-button>
        </div>
        <el-button type="primary" @click="addTeacher()" size="small"
          >新增</el-button
        >
      </div>
    </div>
    <nice-table
      :data="teacherList"
      :showIndex="true"
      :columns="teacherColumns"
      :pagination="teacherPagination"
    >
      <el-table-column
        label="操作"
        align="center"
        width="100"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="editTeacher(scope.row)"
            >编辑</el-button
          >
          <el-button size="small" type="text" @click="deleteTeacher(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <div class="m-h3-btn-box border margin-top30">
      <h3 class="fl">
        班级信息
        <el-radio-group
          v-model="tabStatus"
          size="small"
          @change="selectStudyStatus"
        >
          <el-radio-button label="learning">学习中</el-radio-button>
          <!-- <el-radio-button label="graduated">已毕业</el-radio-button> -->
        </el-radio-group>
      </h3>
      <div class="u-btn-box">
        <el-button type="primary" @click="exportStudent()" size="small"
          >导出学生</el-button
        >
        <!-- <el-button type="primary" @click="batchApply()" size="small"
          >批量报名</el-button
        > -->
        <a
          class="button_txt margin-left10"
          :href="
            'https://jzjx-prod-resource.oss-cn-hangzhou.aliyuncs.com/common/export/student.xlsx?time=' +
              new Date().getTime()
          "
          download="学生导入模板"
          ><el-button type="primary" size="small">下载模板</el-button></a
        >
        <el-button
          type="primary"
          class="margin-left10"
          size="small"
          @click="exportStudentId()"
          >班级id列表</el-button
        >
        <div class="margin-left10 margin-right10">
          <el-button type="primary" class="u-btn" size="small"
            ><updateFile
              accpetObj="xls,xlsx,"
              @updata="file => importStudentObj(file[0].files)"
            />批量导入学生</el-button
          >
        </div>
        <el-button type="primary" @click="addClassHandle()" size="small"
          >新增班级</el-button
        >
        <el-button type="primary" @click="editClassHandle()" size="small"
          >编辑班级</el-button
        >
        <!-- <el-button
          type="primary"
          @click="deleteClassHandle()"
          size="small"
          disabled
          >删除班级</el-button
        > -->
        <el-button type="primary" @click="addStudentHandle()" size="small"
          >新增学生</el-button
        >
      </div>
    </div>
    <div class="margin-top20 margin-bottom10 right">
      <el-radio-group
        v-model="gradeValue"
        size="small"
        @change="changeGrade"
        v-if="tabStatus === 'learning'"
      >
        <el-radio-button
          v-for="(option, i) in gradeNumberList"
          :label="option.grade"
          :key="i"
          >{{ option.gradeName }}({{ option.studentCount }})</el-radio-button
        >
      </el-radio-group>
      <el-radio-group
        v-model="graduteValue"
        size="small"
        @change="changeGraduate"
        v-else
      >
        <el-radio-button
          v-for="(option, ix) in graduteList"
          :label="option.value"
          :key="ix + 500"
          >{{ option.label }}</el-radio-button
        >
      </el-radio-group>
    </div>
    <div class="margin-bottom20 right">
      <el-radio-group v-model="classValue" size="small" @change="changeClass">
        <el-radio-button
          v-for="option in classOptions"
          :label="option.value"
          :key="option.value + 5000"
          >{{ option.label }}</el-radio-button
        >
      </el-radio-group>
    </div>
    <div class="right stu-search">
      <el-form label-width="80px" :inline="true">
        <el-form-item label>
          <el-input
            v-model="search_value"
            placeholder="请输入账号/姓名/联系方式"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getStudentList" size="small"
            >搜索</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <nice-table
      :data="studentList"
      :showSelection="true"
      :columns="studentColumns"
      :pagination="studentPagination"
      @handleSelectionChange="handleSelectionChange"
    >
      <el-table-column
        label="操作"
        align="center"
        width="200"
        slot="opreation"
        fixed="right"
      >
        <template slot-scope="scope">
          <!-- <el-button size="small" type="text" @click="applyHandle(scope.row)"
            >报名</el-button
          > -->
          <el-button size="small" type="text" @click="editStudent(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="text"
            @click="deleteStudent(scope.row)"
            disabled
            >删除</el-button
          >
        </template>
      </el-table-column>
    </nice-table>
    <!-- 空间的模块-->
    <space-basic-info
      v-if="schoolId"
      :basicInfo="basicInfo"
      :schoolId="schoolId"
      :selectEnums="selectArr"
    ></space-basic-info>
    <!-- 组班管理 -->
    <div class="m-h3-btn-box border margin-top30">
      <h3 class="fl">
        组班管理
      </h3>
      <div class="u-btn-box">
        <el-button
          type="primary"
          :disabled="!(zbGradeValue && zbClassValue && zbStudentList.length)"
          @click="exportZbStudent()"
          size="small"
          >导出学生</el-button
        >
        <el-button
          type="primary"
          :disabled="!(zbGradeValue && zbClassValue)"
          @click="addZbStudentHandle()"
          size="small"
          >添加学生</el-button
        >
        <el-button
          type="primary"
          :disabled="!(zbGradeValue && zbClassValue)"
          @click="editZbClassHandle()"
          size="small"
          >编辑班级</el-button
        >
        <el-button type="primary" @click="addZbClassHandle()" size="small"
          >组建班级</el-button
        >
      </div>
    </div>
    <!-- 年级、班级选择 -->
    <div
      class="margin-top20 margin-bottom10 right"
      v-if="zbGradeNumberList.length"
    >
      <el-radio-group
        v-model="zbGradeValue"
        size="small"
        @change="changeZbGrade"
      >
        <el-radio-button
          v-for="(option, i) in zbGradeNumberList"
          :label="option.grade"
          :key="i"
          >{{ option.gradeName }}({{ option.studentCount }})</el-radio-button
        >
      </el-radio-group>
    </div>
    <div class="margin-bottom20 right" v-if="zbClassOptions.length">
      <el-radio-group
        v-model="zbClassValue"
        size="small"
        @change="changeZbClass"
      >
        <el-radio-button
          v-for="option in zbClassOptions"
          :label="option.id"
          :key="option.id"
          >{{ `${option.className}(${option.studentCount})` }}</el-radio-button
        >
      </el-radio-group>
    </div>
    <!-- 选择了年级、班级列表才有操作的必要 -->
    <div v-show="zbGradeValue && zbClassValue">
      <el-form label-width="80px" :model="zbForm" :inline="true">
        <el-form-item label="姓名">
          <el-input
            v-model.trim="zbForm.studentName"
            @keyup.enter.native="getZbStudentList"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="学校">
          <el-select
            v-model="zbForm.schoolId"
            placeholder="请选择学校"
            clearable
          >
            <el-option
              v-for="school in zbSchoolList"
              :key="school.schoolId"
              :label="school.schoolName"
              :value="school.schoolId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级">
          <el-input
            v-model.trim="zbForm.className"
            @keyup.enter.native="getZbStudentList"
            placeholder="请输入班级"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getZbStudentList" size="small"
            >搜索</el-button
          >
          <el-button type="primary" @click="resetZbList" size="small"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <nice-table
        :data="zbStudentList"
        :showSelection="false"
        showIndex
        :columns="zbStudentColumns"
        :pagination="zbStudentPagination"
        @handleSelectionChange="handleZbSelectionChange"
      >
        <el-table-column
          label="操作"
          align="center"
          width="200"
          slot="opreation"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="quitClass(scope.row)"
              >退班</el-button
            >
          </template>
        </el-table-column>
      </nice-table>
    </div>

    <!-- 基站绑定 Begin -->
    <base-station @bindTeach="bindTeach" ref="BaseStation" />
    <!-- 基站绑定 End -->

    <!--新增or编辑组班-->
    <add-edit-zbclass
      v-if="zbClassVisible"
      ref="zbClassForm"
      :selectEnums="selectArr"
      :gradeList="gradeList"
      :schoolId="schoolId"
      @refreshDataList="refreshZbClass"
      :mode="zbmode"
      :classInfo="classInfo"
    ></add-edit-zbclass>
    <!-- 新增学校报课 -->
    <add-school-course
      v-model="schoolCourseVisible"
      ref="schoolCourseForm"
      :gradeList="gradeList"
      @refreshDataList="getenrollmentList"
      :favoureList="selectEnums.nice_order.is_use_coupon"
    ></add-school-course>

    <!-- 新增年级报课 -->
    <grade-apply-course
      v-if="courseVisible"
      ref="courseForm"
      :selectEnums="gradeList"
      :favoureList="selectEnums.nice_order.is_use_coupon"
      @refreshDataList="queryCoursePlanList"
      :schoolId="schoolId"
    ></grade-apply-course>
    <!--新增or编辑教师-->
    <add-update-teacher
      v-if="teacherVisible"
      ref="teacherForm"
      :gradeList="gradeList"
      @refreshDataList="getTeacherList"
      :mode="mode"
      :schoolId="schoolId"
      :selectEnums="selectArr"
    ></add-update-teacher>
    <!--新增or删除班级-->
    <add-delete-class
      v-if="classVisible"
      ref="classForm"
      :gradeList="gradeList"
      @refreshDataList="changeGrade"
      :mode="mode"
      :selectEnums="selectArr"
      :schoolId="schoolId"
    ></add-delete-class>
    <!--新增or编辑学生-->
    <add-update-student
      v-if="studentVisible"
      ref="studentForm"
      :gradeList="gradeList"
      @refreshDataList="getStudentList"
      :title="studentTitle"
      :selectEnums="selectArr"
      :schoolId="schoolId"
    ></add-update-student>
    <!--关联班级-->
    <relate-class
      v-if="relateClassVisible"
      ref="relatedForm"
      :gradeList="gradeList"
      @refreshDataList="getTeacherList"
      :selectEnums="selectArr"
      :schoolId="schoolId"
    ></relate-class>
    <!--报名or批量报名-->
    <batch-apply
      v-if="applyVisible"
      ref="applyForm"
      @refreshDataList="getStudentList"
      :multipleSelection="multipleSelection"
      :applyWay="applyWay"
    ></batch-apply>

    <el-dialog title="课程信息" :visible.sync="dialogTableVisibleCourse">
      <div v-for="(item, index) in schoolCourseList" :key="index + 50">
        <div>{{ item._grade }}</div>
        <el-table :data="item.courseList">
          <el-table-column property="date" label="课程名称">
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column property="name" label="期次">
            <template slot-scope="scope">
              <span>第{{ scope.row.period_sort }}期</span>
            </template>
          </el-table-column>
          <el-table-column property="address" label="上课时间">
            <template slot-scope="scope">
              <span>{{ scope.row.start_date }}-{{ scope.row.end_date }}</span>
              <span>{{ scope.row._frequency }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <csk-dialog
      ref="cskdialog"
      :schoolId="schoolId"
      :classId="zbClassValue"
      @refreshList="initGradeAndClass(zbGradeValue)"
    ></csk-dialog>
    <bind-teach-csk-dialog
      ref="bindTeachCsk"
      :schoolId="schoolId"
      @refreshList="refreshBaseData"
    ></bind-teach-csk-dialog>
  </div>
</template>
<script>
import moment from "moment";
import AddEditZbclass from "./add-edit-zbclass";
import AddSchoolCourse from "./add-school-course";
import AddUpdateTeacher from "./add-update-teacher";
import AddDeleteClass from "./add-delete-class";
import AddUpdateStudent from "./add-update-student";
import SchoolBasicInfo from "./components/school-basic-info";
import MasterBasicInfo from "./components/master-basic-info";
import spaceBasicInfo from "./components/space-basic-info";
import BaseStation from "./components/base-station";
import GradeApplyCourse from "./grade-apply-course";
import RelateClass from "./relate-class";
import BatchApply from "./batch-apply";
import CskDialog from "./csk-dialog";
import BindTeachCskDialog from "./bind-teach-csk-dialog";
import {
  cascadeQuery,
  tableDeleted,
  downloadTemplateFile,
  importData,
  enrollmentList,
  closeOrOpenPlan,
  getCourseByPlanId,
  queryStaffListByType
} from "@/api/api.js";
import {
  getSchoolDetails,
  getPrincipalInfo,
  getGraduates,
  queryCoursePlanList,
  isCloseCoursePlan,
  deletedCoursePlanById,
  getGrade,
  exportStudent,
  getStudentListByCondition,
  updateStudentWechatStatus,
  getClassList,
  setGradeCooperatingStatus,
  adminexportschoolclass,
  operationschoolpositiongetTree
} from "@/api/user";
import {
  adminschoolclasseslist,
  adminschoolteacherlist,
  enumschoolall,
  enumeduall,
  adminimportschoolteacher,
  adminschoolgradeStudentStatistics,
  adminimportschoolstudent,
  adminschoolstudentsave,
  adminschoolstudentlist,
  adminschoolclassesgradeClassesStatistics,
  adminschoolteacherdelete
} from "@/api/lcmapi.js";
import {
  addZb,
  editZb,
  zbSaveStudents,
  getGroupDetail,
  getGradeStudent,
  getClassListStudent,
  getSchoolTree,
  updateGroupStudent,
  getClassStudentLists,
  getGroupStudentList,
  quitGroup,
  getSchoolListByClass,
  exportZbList
} from "@/api/setClass.js";
import { ERROR_CODE } from "@/api/api.js";
import { myEnumsMixins } from "@/utils/mixins";
export default {
  name: "school-detail",
  components: {
    AddUpdateTeacher,
    AddDeleteClass,
    AddUpdateStudent,
    RelateClass,
    BatchApply,
    SchoolBasicInfo,
    MasterBasicInfo,
    GradeApplyCourse,
    AddSchoolCourse,
    spaceBasicInfo,
    AddEditZbclass,
    CskDialog,
    BindTeachCskDialog,
    BaseStation,
    updateFile: resolve => require(["@/components/updateFile.vue"], resolve)
  },
  mixins: [myEnumsMixins],
  data() {
    return {
      url: "",
      search_value: "", // 搜索
      mode: "",
      graduteValue: "",
      graduteList: [],
      applyWay: "",
      schoolId: "",
      applyVisible: false,
      courseVisible: false,
      schoolCourseVisible: false,
      dialogTableVisibleCourse: false, // 课程信息
      schoolCourseList: [],
      schoolCourseLists: [],
      options: [],
      basicInfo: {},
      masterInfo: {},
      gradeList: [],
      selectArr: {},
      jobOptions: [
        { label: "教务组长", value: "1" },
        { label: "年级主任", value: "2" }
      ],
      courseSchoolPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCourseSchoolCurrentChange,
        handleSizeChange: this.handleCourseSchoolSizeChange
      },
      courseSchoolColumns: [
        {
          label: "创建日期",
          prop: "create_time",
          width: "100"
        },
        {
          label: "包含年级",
          prop: "grade_name",
          width: "150"
        },
        {
          label: "包含课程",
          prop: "course_count",
          width: "150",
          extends: [
            {
              clickFunction: val => {
                this.viewDetail(val);
              }
            }
          ]
        },
        {
          label: "辅导老师",
          prop: "tutor_name"
        },
        {
          label: "拟接入人数",
          prop: "plan_num"
        },
        {
          label: "操作人",
          prop: "real_name"
        }
      ],

      studentTitle: "",
      teacherList: [],
      teacherColumns: [
        {
          label: "账号",
          prop: "username",
          width: 150,
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val, "username");
              },
              isAccountView: true,
              key: "username"
            }
          ]
        },
        {
          label: "姓名",
          prop: "realName"
        },
        {
          label: "性别/年龄",
          prop: "sexAndAge"
        },
        {
          label: "职位",
          prop: "positionName"
        },
        {
          label: "班级",
          prop: "relateClass",
          width: 200,
          extends: [
            {
              clickFunction: val => {
                this.relateClass(val);
              },
              isImg: true,
              // icon: "el-icon-link",
              imgurl: require("@/assets/img/link.svg")
            }
          ]
        },
        {
          label: "学科",
          prop: "subjects",
          extends: [
            {
              filterFunction: val => {
                return this.$filterEnumsArr(val, this.selectArr.subject).join(
                  ","
                );
              }
            }
          ]
        },
        {
          label: "联系方式",
          prop: "mobile",
          width: 150,
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val, "mobile");
              },
              key: "mobile",
              isView: true
            }
          ]
        }
      ],
      teacherPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleTeacherCurrentChange,
        handleSizeChange: this.handleTeacherSizeChange
      },
      studentPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleStudentCurrentChange,
        handleSizeChange: this.handleStudentSizeChange
      },
      coursePlanPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCoursePlanCurrentChange,
        handleSizeChange: this.handleCoursePlanSizeChange
      },
      classOptions: [],
      tabStatus: "learning",
      classValue: "",
      gradeValue: "",
      studentList: [],
      gradeNumberList: [],
      gradeConfig: {},
      studentColumns: [
        {
          label: "账号",
          prop: "username",
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val, "username");
              },
              isAccountView: true,
              key: "username"
            }
          ]
        },
        {
          label: "姓名",
          prop: "realName"
        },
        {
          label: "入学年份",
          prop: "startYear"
        },
        {
          label: "老师匹配状态",
          prop: "subjectList",
          extends: [
            {
              filterFunction: val => {
                console.log(val);
                if (val) {
                  return this.filtersubjectList(val);
                } else {
                  return "";
                }
              }
            }
          ]
        },
        {
          label: "联系方式",
          prop: "mobile",
          width: 150,
          extends: [
            {
              clickFunction: val => {
                this.viewPhone(val, "mobile");
              },
              key: "mobile",
              isView: true
            }
          ]
        }
      ],
      coursePlanColumns: [
        {
          label: "创建日期",
          prop: "create_time",
          width: "150"
        },
        {
          label: "标题",
          prop: "course_title"
        },
        {
          label: "包含课程",
          prop: "course_period_list",
          isArray: true
        },
        {
          label: "学生年级",
          prop: "grade_name",
          width: "80"
        },
        {
          label: "辅导老师",
          prop: "real_name",
          width: "150"
        },
        {
          label: "报名链接",
          prop: "enroll_link",
          width: "100",
          extends: [
            {
              clickFunction: val => {
                this.copyUrl(val);
              },
              isBtn: true,
              btn_name: "复制链接"
            }
          ]
        },
        {
          label: "操作人",
          prop: "operator_name",
          width: "80"
        }
      ],
      multipleSelection: [],
      teacherVisible: false,
      classVisible: false,
      studentVisible: false,
      relateClassVisible: false,
      coverageGrade: [],
      courseList: [],
      schoolCourseList: [],
      loadingPage: false,
      teaterFileList: [],
      studentFileList: [],
      // 组班管理
      zbClassVisible: false,
      zbGradeValue: "",
      zbClassValue: "",
      zbGradeNumberList: [],
      zbChangeGrade: [],
      zbClassOptions: [],
      zbForm: {
        studentName: "",
        schoolId: "",
        className: ""
      },
      zbSchoolList: [],
      zbStudentList: [],
      zbStudentColumns: [
        {
          label: "账号",
          prop: "userName",
          width: 150
        },
        {
          label: "姓名",
          prop: "studentName"
        },
        {
          label: "学校",
          prop: "schoolName"
        },
        {
          label: "班级",
          prop: "className"
        }
      ],
      zbStudentPagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleZbStudentCurrentChange,
        handleSizeChange: this.handleZbStudentSizeChange
      },
      zbmode: "add",
      zbClassVisible: false,
      classInfo: {
        initGrade: "",
        className: "",
        classId: ""
      }
    };
  },
  activated() {
    console.log("activated");
    this.$store.dispatch("common/saveRegion");
    this.url = this.$http.adornUrl(
      `/questionlib/sys/oss/upload?token=${this.$cookie.get("token")}`
    );
    this.schoolId = "";
    this.$nextTick(() => {
      this.schoolId = this.$route.params.id;
      this.search_value = "";

      this.queyEnumByTableName().then(res => {
        this.getTeacherList();
        this.getSchoolDetails();
      });
      this.initGradeAndClass();
    });
  },
  methods: {
    bindTeach(row) {
      console.log("bindTeach", row);
      this.$refs.bindTeachCsk.init(row);
    },
    // 绑定教师刷新数据
    refreshBaseData() {
      this.$refs.BaseStation.getList();
    },
    // 获取年级，班级等初始化操作
    initGradeAndClass(grade) {
      this.getGradeStudent().then(() => {
        if (this.zbGradeNumberList.length) {
          // 年级切换，则清班级
          if (this.zbGradeValue !== grade) {
            this.zbClassValue = '';
          }
          this.zbGradeValue = grade || this.zbGradeNumberList[0].grade;
          this.getClassListStudent();
        } else {
          this.zbGradeValue = "";
          this.zbClassValue = "";
        }
      });
    },
    // 新增和编辑组班，后刷新列表
    refreshZbClass(form) {
      console.log("refreshZbClass", form);
      this.zbGradeValue =
        form && form.initGrade ? form.initGrade : this.zbGradeValue;
      this.getClassListStudent(form, true);
    },
    // 获取组班年级列表
    getGradeStudent() {
      return new Promise(async (resolve, reject) => {
        let res = await getGradeStudent({
          schoolId: this.schoolId,
          classType: "group"
        });
        console.log("getGradeStudent", res);
        if (res[1] && res[1].code === 0) {
          this.zbGradeNumberList = res[1].data || [];
          resolve();
        } else {
          reject(res[1].msg);
        }
      });
    },

    // 获取年级下的班级
    // form.initGrade 年级
    // form.classId 班级
    // isEnd 班级是否增加到最后
    async getClassListStudent(form, isEnd = false) {
      console.log("getClassListStudent", this.zbClassValue);
      let res = await getClassListStudent({
        schoolId: this.schoolId,
        grade: this.zbGradeValue,
        classType: "group"
      });
      console.log("getClassListStudent", res);
      if (res[1] && res[1].code === 0) {
        this.zbClassOptions = res[1].data || [];
        if (this.zbClassOptions.length) {
          // form中的classId存在则用，其次isEnd生效，则选择班级最后一个；否则判定之前是否选中班级；
          this.zbClassValue =
            form && form.classId
              ? form.classId
              : isEnd
              ? this.zbClassOptions[this.zbClassOptions.length - 1].id
              : this.zbClassValue
              ? this.zbClassValue
              : this.zbClassOptions[0].id;
          this.resetZbList();
        } else {
          this.zbClassValue = "";
        }
      }
    },
    // 查询组班列表
    getZbStudentList() {
      this.cloneSearchParams = this.$deepcopy(this.zbForm);
      console.log("查询组班列表");
      let params = {
        classId: this.zbClassValue,
        currPage: this.zbStudentPagination.pageNum,
        pageSize: this.zbStudentPagination.pageSize,
        schoolId: this.zbForm.schoolId,
        className: this.zbForm.className,
        studentName: this.zbForm.studentName
      };
      getGroupStudentList(params).then(res => {
        if (res[1] && res[1].code == 0) {
          let formData = res[1].data;
          // 如果学生列表为空，且不是第一页，则重新请求最大页码totalPage数据
          if (formData.studentList.length === 0 && formData.currPage > 1) {
            this.zbStudentPagination.pageNum = formData.totalPage || 1;
            this.getZbStudentList();
          } else {
            this.zbStudentList = formData.studentList;
            this.zbStudentPagination.pageNum = formData.currPage;
            this.zbStudentPagination.total = formData.totalCount;
          }
        } else {
          this.zbStudentList = [];
        }
      });
      // 获取列表（学校）筛选条件
      getSchoolListByClass({
        classId: this.zbClassValue
      }).then(res => {
        if (res[1] && res[1].code == 0) {
          this.zbSchoolList = res[1].data || [];
        }
      });
    },
    changeZbGrade() {
      this.zbClassValue = "";
      this.getClassListStudent();
    },
    changeZbClass() {
      this.resetZbList();
    },
    // 重置查询组班列表
    resetZbList() {
      this.zbStudentPagination.pageNum = 1;
      this.zbForm = this.$options.data().zbForm;
      this.getZbStudentList();
    },
    // 退出班级
    quitClass(row) {
      console.log("退出班级", row);
      let params = {
        studentId: row.studentId,
        classId: this.zbClassValue
      };
      this.$confirm("确认退班?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          quitGroup(params).then(res => {
            if (!res[1]) {
              return;
            }

            if (res[1].code == 0) {
              this.$message.success("退班成功");
              this.initGradeAndClass(this.zbGradeValue);
            } else if (res[1].code === ERROR_CODE.REFRESH_LIST) {
              this.getZbStudentList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消退班"
          });
        });
    },
    // 列表操作处理
    handleZbSelectionChange() {},
    // 分页处理
    handleZbStudentCurrentChange(val) {
      this.zbStudentPagination.pageNum = val;
      this.getZbStudentList();
    },
    handleZbStudentSizeChange(val) {
      this.zbStudentPagination.pageSize = val;
      this.getZbStudentList();
    },
    // 组建班级
    addZbClassHandle() {
      this.zbmode = "add";
      this.zbClassVisible = true;
      this.$nextTick(() => {
        this.$refs.zbClassForm.init();
      });
    },
    editZbClassHandle() {
      this.zbmode = "edit";
      this.zbClassVisible = true;
      getGroupDetail({
        classId: this.zbClassValue
      }).then(res => {
        if (res[1] && res[1].code == 0) {
          let info = res[1].data;
          console.log("edit zbClassValue", info);
          this.$refs.zbClassForm.init(info);
        } else {
          // this.$message.info(res[1].msg);
        }
      });
    },
    addZbStudentHandle() {
      this.$nextTick(() => {
        // schoolId 字符串
        this.$refs.cskdialog.init("" + this.schoolId);
      });
    },
    formatDate() {
      let Dates = new Date();
      let Y = Dates.getFullYear();
      let M = Dates.getMonth() + 1;
      let D = Dates.getDate();
      let times = Y + (M < 10 ? '0' : '') + M + (D < 10 ? '0' : '') + D;
      return times;
    },
    getClassName(classId) {
      let className = '';
      this.zbClassOptions.forEach(item => {
        if (item.id == classId) {
          className = item.className;
        }
      })
      return className;
    },
    async exportZbStudent() {
      // 搜索后，深拷贝查询条件
      let params = this.cloneSearchParams || this.zbForm;
      let res = await exportZbList({
        schoolId: params.schoolId,
        classId: this.zbClassValue,
        className: params.className,
        studentName: params.studentName
      });
      if (res.status === 200) {
        let date = this.formatDate();
        let filename = decodeURI(`${this.getClassName(this.zbClassValue)}-${date}.xlsx`);
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
      // window.open(res[1])
    },
    // 查找当前老师的科目
    filtersubjectList(val) {
      let newgradeName = [];
      if (!val) {
        return "";
      }
      val.forEach(item => {
        newgradeName.push(this.$filterEnums(item, this.selectArr.subject));
      });
      return newgradeName.join(",");
    },
    // 获取枚举
    async queyEnumByTableName() {
      return new Promise(async (a, b) => {
        // 获取学校的枚举接口
        let selectArr = {
          schoolType: [], // 学校性质
          level: [], // 学校等级
          studentScale: [], // 学生规模
          isOpen: [], // 状态
          coverageGrade: [] // 覆盖年级
        };
        // 获取学校的枚举
        let enumschoolallRes = await enumschoolall({});
        if (enumschoolallRes[0]) {
          return;
        }
        // 获取老师的枚举
        let enumeduallRes = await enumeduall({});
        if (enumeduallRes[0]) {
          return;
        }
        // 获取当前学校授课年级的枚举
        let adminschoolgradeStudentStatisticsRes = await adminschoolgradeStudentStatistics(
          {
            schoolId: this.schoolId,
            classType: "normal"
          }
        );
        if (adminschoolgradeStudentStatisticsRes[0]) {
          return;
        }
        // 获取职位的枚举
        let operationschoolpositiongetTreeRes = await operationschoolpositiongetTree(
          { node_id: 1 }
        );
        if (operationschoolpositiongetTreeRes[0]) {
          return;
        }
        let grade = [];
        adminschoolgradeStudentStatisticsRes[1].data.forEach(item => {
          grade.push({
            name: item.gradeName,
            id: item.grade
          });
        });
        this.gradeNumberList = adminschoolgradeStudentStatisticsRes[1].data;
        if (this.gradeNumberList && this.gradeNumberList.length) {
          this.gradeValue = this.gradeNumberList[0].grade;
          this.changeGrade();
        }
        this.selectArr = {
          ...enumschoolallRes[1].data,
          ...enumeduallRes[1].data
        };
        this.selectArr.grade = grade;
        this.selectArr.jobOptions =
          operationschoolpositiongetTreeRes[1].data.node.children;
        this.selectArr.level = [
          {
            label: "A",
            value: 1
          },
          {
            label: "B",
            value: 2
          },
          {
            label: "C",
            value: 3
          }
        ];
        this.selectArr.coverageGrade = [
          {
            label: "幼儿园",
            value: 1
          },
          {
            label: "小学",
            value: 2
          },
          {
            label: "初中",
            value: 3
          },
          {
            label: "高中",
            value: 4
          }
        ];
        a();
      });
    },
    viewDetail(val) {
      getCourseByPlanId({ id: val.id }).then(res => {
        this.dialogTableVisibleCourse = true;
        this.schoolCourseLists = res[1].data;
        this.schoolCourseLists.forEach((item, index) => {
          item._grade = this.$filterEnums(item.grade, this.gradeList);
          item.courseList.forEach(_i => {
            _i._frequency =
              "周" + this.$filterFrequency(JSON.parse(_i.frequency));
          });
        });
        console.log("schoolCourseLists", this.schoolCourseLists);
      });
      console.log("val", val);
    },
    // 获取当前年级是否停止合作
    async getGradeCooperatingStatus(cooperatingStatus) {
      let { gradeConfig } = this;

      let res = await setGradeCooperatingStatus({
        "nice_school_coverageGrade_detail.school_id": this.schoolId,
        "nice_school_coverageGrade_detail.grade_id": gradeConfig.value,
        "nice_school_coverageGrade_detail.cooperating_status": gradeConfig.cooperatingStatus
          ? 0
          : 1
      }); // 获取当前的学校是否已经停止合作
      if (res[0]) {
        return;
      }
      gradeConfig.cooperatingStatus = gradeConfig.cooperatingStatus ? 0 : 1;
      this.gradeConfig = { ...{}, ...gradeConfig };
    },
    // 获取市场负责人以及代理商的数组
    async getQueryStaffListByType() {
      let { nice_school } = this.selectEnums;
      let obj = {};
      let market_id = await queryStaffListByType({ "sys_user.user_type": "6" }); // 市场负责人的列表
      if (market_id[0]) {
        return;
      }
      obj.market_id = market_id[1].data.list;
      obj.market_id.forEach(item => {
        item.label = item.name;
        item.value = item.user_id;
      });
      let school_agents = await queryStaffListByType({
        "sys_user.user_type": "14"
      }); // 代理商的列表
      if (school_agents[0]) {
        return;
      }
      obj.school_agents = school_agents[1].data.list;
      obj.school_agents.forEach(item => {
        item.label = item.name;
        item.value = item.user_id;
      });
      this.selectEnums.nice_school = { ...nice_school, ...obj };
    },
    // 导出学生
    async exportStudent() {
      let res = await exportStudent({
        schoolId: this.schoolId,
        grade: this.gradeValue,
        classId: this.classValue
      });
      if (res.status === 200) {
        let filename = decodeURI("导出学生.xlsx");
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
      // window.open(res[1])
    },
    async exportStudentId() {
      let res = await adminexportschoolclass({
        schoolId: this.schoolId
      });
      if (res.status === 200) {
        let filename = decodeURI("导出学生Id.xlsx");
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
    },
    // 学校报课列表
    getenrollmentList() {
      let params = {
        currPage: "1",
        pageSize: 10,
        school_id: this.schoolId
      };
      enrollmentList(params).then(res => {
        if (res[0]) {
          return;
        }
        let data = res[1];
        this.tabStatus = "learning";
        if (data && data.code === 0) {
          this.schoolCourseList = data.data.list;
          console.log("res", res);
        }
      });
    },
    // 学校报课开关
    setcloseOrOpenPlan(e, item) {
      console.log(e, item);
      let params = {
        "nice_school_enrollment_plan.id": item.id,
        "nice_school_enrollment_plan.is_close": item.is_close
      };
      closeOrOpenPlan(params).then(res => {
        if (res[1].code == 0) {
          this.$message.success("设置成功");
        } else {
          this.$message.error("设置失败");
        }
      });
    },
    handleCourseSchoolCurrentChange(val) {
      this.courseSchoolPagination.pageNum = val;
    },
    handleCourseSchoolSizeChange(val) {
      this.courseSchoolPagination.pageSize = val;
    },

    updateStudentWechatStatus(item) {
      this.$confirm(
        `${
          item.wechat_status
            ? "确认修改为未添加该学生微信？？"
            : "确认添加该学生微信？"
        }`,
        "添加微信确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(async () => {
          let res = await updateStudentWechatStatus({
            "nice_user_base.user_id": item.user_id,
            "nice_user_base.wechat_status": item.wechat_status ? 0 : 1
          });
          if (res[0]) {
            return;
          }
          if (res[1].code === 0) {
            this.$message.success("修改成功！");
            this.getStudentList();
          }
        })
        .catch(() => {});
    },
    async getSchoolDetails() {
      let res = await getSchoolDetails({ schoolId: Number(this.schoolId) });
      if (res[0]) {
        return;
      }
      let data = res[1];
      this.tabStatus = "learning";
      if (data && data.code === 0) {
        this.basicInfo = data.data;
        this.basicInfo.region = [
          +this.basicInfo.province,
          +this.basicInfo.city,
          +this.basicInfo.area
        ];
        this.basicInfo.master = data.data.master;
        this.basicInfo.coverageGrade = [];
        this.gradeList = [];
        let coverageGrade = [];
        let coverageGradeName = [];
        // this.queryCoursePlanList();
        this.basicInfo.nurseryGrade &&
          coverageGrade.push(1) &&
          coverageGradeName.push("幼儿园");
        this.basicInfo.juniorGrade &&
          coverageGrade.push(2) &&
          coverageGradeName.push("小学");
        this.basicInfo.middleGrade &&
          coverageGrade.push(3) &&
          coverageGradeName.push("初中");
        this.basicInfo.highGrade &&
          coverageGrade.push(4) &&
          coverageGradeName.push("高中");
        this.basicInfo.coverageGrade = [];
        if (coverageGrade && coverageGrade.length) {
          this.basicInfo.coverageGrade = coverageGrade;
          this.basicInfo.coverageGradeName = coverageGradeName;
        }
        // this.getGrade()
      } else {
        this.$message.error(data.msg);
      }
    },
    async getGrade() {
      let gradeNumberList = [];
      let res = await getGrade({
        grade: this.basicInfo.coverageGradeName,
        school_id: this.schoolId
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        res[1].data.forEach(ele => {
          this.gradeList.push({
            label: ele.display_value,
            value: ele.t_id
          });
          gradeNumberList.push({
            label: ele.display_value + "(" + ele.studentNum + ")",
            value: ele.t_id,
            cooperatingStatus: ele.cooperatingStatus
          });
          this.gradeNumberList = gradeNumberList;
        });
        if (this.basicInfo.school_head_id) {
          this.getPrincipalInfo(this.basicInfo.school_head_id);
        } else {
          this.masterInfo = {};
        }
        if (this.gradeList && this.gradeList.length) {
          this.gradeValue = this.gradeList[0].value;
          this.changeGrade();
        }
        this.getTeacherList();
      }
    },
    async queryCoursePlanList() {
      this.coursePlanPagination.total = 0;
      let res = await queryCoursePlanList({
        school_id: this.schoolId,
        currPage: this.coursePlanPagination.pageNum,
        pageSize: this.coursePlanPagination.pageSize
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.courseList = res[1].coursePlanList;
        if (res[1].coursePlanList && res[1].coursePlanList.length) {
          this.coursePlanPagination.total = res[1].coursePlanList.length;
          res[1].coursePlanList.forEach(ele => {
            ele.create_time = ele.create_time.substring(0, 16);
            ele.course_title = this.basicInfo.school_name + ele.title;
            if (ele.coursePeriodList && ele.coursePeriodList.length) {
              ele.course_period_list = ele.coursePeriodList.map(ele => {
                return (
                  ele.course_name +
                  "/" +
                  this.$convertNum(ele.period_sort) +
                  "期"
                );
              });
            }
          });
        }
      }
    },
    addSchoolCourse() {
      this.schoolCourseVisible = true;
      this.$nextTick(() => {
        this.$refs.schoolCourseForm.init();
      });
    },
    editSchoolCourse(row) {
      console.log(row);
      this.schoolCourseVisible = true;
      this.$nextTick(() => {
        this.$refs.schoolCourseForm.getdetailsinfo(row.id);
      });
    },

    async openUrl(row) {
      this.$confirm(`确定进行${row.is_close ? "开启" : "关闭"}操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let res = await isCloseCoursePlan({
            table_name: "nice_school_course_plan",
            update: [
              {
                is_close: row.is_close ? 0 : 1
              }
            ],
            where: [
              {
                id: row.id
              }
            ]
          });
          if (res[0]) {
            return;
          }
          if (res[1] && res[1].code === 0) {
            this.$message.success(`${row.is_close ? "开启" : "关闭"}成功！`);
            this.queryCoursePlanList();
          }
        })
        .catch(() => {});
    },
    copyUrl(row) {
      var Url2 = row.enroll_link;
      var oInput = document.createElement("input");
      oInput.value = Url2;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.className = "oInput";
      oInput.style.display = "none";
      this.$message({
        message: "复制成功!",
        type: "success"
      });
    },
    deleteCourse(row) {
      this.$confirm("确定删除操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let res = await deletedCoursePlanById([
            {
              table_name: "nice_school_course_plan",
              where: {
                id: [row.id]
              }
            }
          ]);
          if (res[0]) {
            return;
          }
          if (res[1] && res[1].code === 0) {
            this.$message.success("删除成功！");
            this.queryCoursePlanList();
          }
        })
        .catch(() => {});
    },
    addApplyCourse() {
      this.courseVisible = true;
      this.$nextTick(() => {
        this.$refs.courseForm.init();
      });
    },
    editCourse(item) {
      this.courseVisible = true;
      this.$nextTick(() => {
        this.$refs.courseForm.init(item.id);
      });
    },
    // 获取届数与届数下的班级
    async getGraduates() {
      this.graduteList = [];
      this.classOptions = [];
      this.studentList = [];
      this.studentPagination.total = 0;
      let res = await getGraduates({
        "nice_school_class_student.school_id": this.schoolId
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        if (res[1].data.list && res[1].data.list.length) {
          res[1].data.list.forEach((ele, index) => {
            let classList = [];
            if (ele.rel_class) {
              ele.rel_class.split(",").forEach(item => {
                classList.push({
                  label: item.split("-")[1],
                  value: item.split("-")[0]
                });
              });
            }
            this.graduteList.push({
              label: ele.graduates,
              value: index,
              classList: classList
            });
            this.graduteValue = this.graduteList[0].value;
            this.classOptions = this.graduteList[0].classList;
            if (
              this.graduteList[0].classList &&
              this.graduteList[0].classList.length
            ) {
              this.classValue = this.graduteList[0].classList[0].value;
              this.studentPagination.pageNum = 1;
              this.getStudentList();
            } else {
              this.classValue = "";
            }
          });
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    changeGraduate() {
      this.graduteList.forEach((ele, index) => {
        if (ele.value === this.graduteValue) {
          this.classOptions = ele.classList;
          if (this.classOptions && this.classOptions.length) {
            this.classValue = this.classOptions[0].value;
            this.studentPagination.pageNum = 1;
            this.getStudentList();
          } else {
            this.classValue = "";
          }
        }
      });
    },
    async getPrincipalInfo(id) {
      let res = await getPrincipalInfo({ "nice_teacher_info.user_id": id });
      if (res[0]) {
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.masterInfo = data.data.list[0];
      } else {
        this.$message.error(data.msg);
      }
    },
    // 批量导入教师
    async importObj(e) {
      let formData = new FormData();
      formData.append("file", e);
      formData.append("schoolId", this.schoolId);
      let res = await adminimportschoolteacher(formData);
      if (res[0]) {
        return;
      }
      this.queyEnumByTableName().then(() => {
        this.getTeacherList();
      });
      // this.$ref.uploadExl.clearFiles();
      this.teaterFileList = [];
    },
    // 批量导入学生
    async importStudentObj(file) {
      console.log(file);
      let formData = new FormData();
      formData.append("file", file);
      formData.append("schoolId", this.schoolId);

      let res = await adminimportschoolstudent(formData);
      if (res[0]) {
        return;
      }
      this.queyEnumByTableName().then(() => {
        this.getStudentList();
      });
      // this.$ref.uploadStuExl.clearFiles();
      this.studentFileList = [];
    },
    // 上传前验证
    beforeUpload(file) {
      const isExcel =
        file.type === "application/vnd.ms-excel" ||
        file.type ===
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const isLt100M = file.size / 1024 / 1024 < 200;

      if (!isExcel) {
        this.$message.error("上传的文件只能是 xls 或 xlsx 格式!");
      }
      if (!isLt100M) {
        this.$message.error("上传的文件大小不能超过 200MB!");
      }
      return isExcel && isLt100M;
    },
    async downTeacherHandle() {
      let res = await downloadTemplateFile({
        data: [
          { header: "账号(必填)", tableandfield: "sys_user.username" },
          {
            header: "姓名(必填)",
            tableandfield: "sys_user.sys_user_nice_user_base.real_name"
          },
          {
            header: "性别",
            tableandfield: "sys_user.sys_user_nice_user_base.sex"
          },
          {
            header: "年龄",
            tableandfield: "sys_user.sys_user_nice_user_base.age"
          },
          {
            header: "职位",
            tableandfield: "sys_user.sys_user_school_teacher.position"
          },
          {
            header: "学科",
            tableandfield:
              "sys_user.sys_user_school_teacher_class.subject:sys_user.sys_user_school_teacher.subject"
          },
          {
            header: "联系方式",
            tableandfield: "sys_user.sys_user_nice_user_base.mobile"
          }
        ]
      });
      if (res.status === 200) {
        let filename = decodeURI("教师模板下载.xls");
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
    },
    selectStudyStatus() {
      this.studentPagination.pageNum = 1;
      this.studentPagination.pageSize = 10;
      if (this.tabStatus === "graduated") {
        this.getGraduates();
      } else {
        if (this.gradeList && this.gradeList.length) {
          this.gradeValue = this.gradeList[0].value;
          this.changeGrade();
        }
      }
    },
    async changeGrade() {
      this.studentPagination.pageNum = 1;
      this.studentPagination.pageSize = 10;
      this.studentPagination.total = 0;
      this.classOptions = [];
      let res = await adminschoolclassesgradeClassesStatistics({
        schoolId: this.schoolId,
        grade: this.gradeValue,
        classType: "normal"
      });
      let gradeConfig = {};
      this.selectArr.grade.forEach(item => {
        if (item.name == this.gradeValue) {
          gradeConfig = item;
        }
      });
      this.gradeConfig = gradeConfig;

      this.gradeConfig.cooperatingStatus = gradeConfig.cooperatingStatus;
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        if (res[1].data && res[1].data.length) {
          let totalNum = 0;
          res[1].data.forEach(ele => {
            totalNum = totalNum + Number(ele.studentCount);
            this.classOptions.push({
              label: ele.className + "(" + Number(ele.studentCount) + ")",
              value: ele.id
            });
          });
          this.classOptions.unshift({
            label: "全部" + "(" + totalNum + ")",
            value: ""
          });
          this.classValue =
            this.classOptions && this.classOptions.length
              ? this.classOptions[0].value
              : "";
          this.getStudentList();
        } else {
          this.classOptions = [];
          this.studentList = [];
        }
      } else {
        this.$message.error(res[1].msg);
      }
    },
    changeClass() {
      this.studentPagination.pageNum = 1;
      this.studentPagination.pageSize = 10;
      this.getStudentList();
    },
    batchApply() {
      if (!this.multipleSelection.length) {
        this.$alert("请选择需要报名的学生", "提示", {
          confirmButtonText: "关闭",
          callback: action => {}
        });
      } else {
        this.applyVisible = true;
        this.applyWay = "batch";
        this.$nextTick(() => {
          this.$refs.applyForm.init();
        });
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async downStudent() {
      let res = await downloadTemplateFile({
        data: [
          { header: "账号", tableandfield: "sys_user.username" },
          {
            header: "姓名",
            tableandfield: "sys_user.sys_user_nice_user_base.real_name"
          },
          {
            header: "联系方式",
            tableandfield:
              "sys_user.username:sys_user.sys_user_nice_user_base.mobile"
          },
          {
            header: "性别",
            tableandfield: "sys_user.sys_user_nice_user_base.sex"
          },
          {
            header: "邮寄地址",
            tableandfield: "sys_user.sys_user_nice_user_base.address"
          },
          {
            header: "状态",
            tableandfield: "sys_user.sys_user_nice_student.status"
          }
        ]
      });
      if (res.status === 200) {
        let filename = decodeURI("学生模板下载.xls");
        filename = filename.replace(/\"/g, "");
        this.$downloadExcel(res.data, filename);
      }
    },
    relateClass(row) {
      this.relateClassVisible = true;
      this.$nextTick(() => {
        this.$refs.relatedForm.init(row);
      });
    },
    async getTeacherList() {
      let res = await adminschoolteacherlist({
        schoolId: this.schoolId,
        pageNum: this.teacherPagination.pageNum,
        pageSize: this.teacherPagination.pageSize
      });
      if (res[0]) {
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.teacherPagination.total = data.data.totalCount;
        this.teacherList = [];
        data.data.list.forEach(ele => {
          ele.isView = false;
          ele.isAccountView = false;
          ele.sexName = ele.sex === 1 ? "女" : ele.sex === 0 ? "男" : "未知";
          ele.age = ele.age ? ele.age : "未知";
          ele.sexAndAge = ele.sexName + "/" + ele.age;
          ele.relateClass = "";
          if (ele.classesList && ele.classesList[0]) {
            ele.classesList.forEach(item => {
              if (ele.relateClass) {
                ele.relateClass =
                  ele.relateClass +
                  "," +
                  this.$filterEnums(+ele.grade, this.selectArr.grade) +
                  item.className +
                  "-" +
                  this.$filterEnums(+item.subject, this.selectArr.subject);
              } else {
                ele.relateClass =
                  ele.relateClass +
                  this.$filterEnums(+item.grade, this.selectArr.grade) +
                  item.className +
                  "-" +
                  this.$filterEnums(+item.subject, this.selectArr.subject);
              }
            });
          } else {
            ele.relateClass = "未关联";
          }
        });
        this.teacherList = data.data.list;
      } else {
        this.$message.error(data.msg);
      }
    },
    async getStudentList() {
      let res = await adminschoolstudentlist({
        schoolId: Number(this.schoolId),
        grade: this.gradeValue,
        schoolClassId: this.classValue || null,
        keywords: this.search_value,
        currPage: this.studentPagination.pageNum,
        pageSize: this.studentPagination.pageSize
      });
      if (res[0]) {
      }
      let data = res[1];
      console.log(data);
      if (data && data.code === 0) {
        this.studentPagination.total = data.data.totalCount;
        data.data.list.forEach(ele => {
          ele.isView = false;
          ele.isAccountView = false;
          ele.status = ele.use_status ? "已启用" : "未启用";
        });
        this.studentList = data.data.list;
      } else {
        this.$message.error(data.msg);
      }
    },
    addTeacher() {
      this.teacherVisible = true;
      this.mode = "addTeacher";
      this.$nextTick(() => {
        this.$refs.teacherForm.init();
      });
    },
    handleTeacherCurrentChange(val) {
      this.teacherPagination.pageNum = val;
      this.getTeacherList();
    },
    handleTeacherSizeChange(val) {
      this.teacherPagination.pageSize = val;
      this.getTeacherList();
    },
    handleStudentCurrentChange(val) {
      this.studentPagination.pageNum = val;
      this.getStudentList();
    },
    handleStudentSizeChange(val) {
      this.studentPagination.pageSize = val;
      this.getStudentList();
    },
    handleCoursePlanCurrentChange(val) {
      this.coursePlanPagination.pageNum = val;
      this.queryCoursePlanList();
    },
    handleCoursePlanSizeChange(val) {
      this.coursePlanPagination.pageSize = val;
      this.queryCoursePlanList();
    },
    editTeacher(row) {
      this.teacherVisible = true;
      this.mode = "editTeacher";
      this.$nextTick(() => {
        this.$refs.teacherForm.init(this.$deepcopy(row));
      });
    },
    deleteTeacher(row) {
      this.$confirm("确定删除教师？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          adminschoolteacherdelete({
            schoolId: this.schoolId,
            teacherId: row.teacherId
          }).then(res => {
            if (res[0]) {
              return;
            }
            let data = res[1];
            if (data && data.code === 0) {
              this.$message.success("删除教师成功！");
              this.getTeacherList();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    async tableDeleted(type, id) {
      let _api = type == "teacher" ? adminschoolteacherdelete : aa;
      let res = await _api([
        {
          table_name: "sys_user",
          where: {
            user_id: [id]
          }
        }
      ]);
      if (res[0]) {
        return;
      }
      let data = res[1];
      if (data && data.code === 0) {
        this.$message.success(
          type === "teacher" ? "删除教师成功！" : "删除学生成功！"
        );
        type === "teacher" && this.getTeacherList();
        type === "student" && this.getStudentList();
      } else {
        this.$message.error(data.msg);
      }
    },
    viewPhone(row, type) {
      this.teacherList.forEach(ele => {
        if (ele.id !== row.id) {
          if (type === "mobile") {
            ele.isView = false;
          } else {
            ele.isAccountView = false;
          }
        }
      });
      type === "mobile"
        ? (row.isView = !row.isView)
        : (row.isAccountView = !row.isAccountView);
      this.teacherList = [...this.teacherList];
    },
    viewStudentPhone(row) {
      this.studentList.forEach(ele => {
        if (ele.user_id !== row.user_id) {
          ele.isAccountView = false;
        }
      });
      row.isAccountView = !row.isAccountView;
      this.studentList = [...this.studentList];
    },
    addClassHandle() {
      this.mode = "add";
      this.classVisible = true;
      this.$nextTick(() => {
        this.$refs.classForm.init();
      });
    },
    editClassHandle() {
      this.mode = "edit";
      this.classVisible = true;
      this.$nextTick(() => {
        this.$refs.classForm.init();
      });
    },
    deleteClassHandle() {
      this.mode = "delete";
      this.classVisible = true;
      this.$nextTick(() => {
        this.$refs.classForm.init();
      });
    },
    addStudentHandle() {
      this.studentVisible = true;
      this.studentTitle = "新增学生";
      this.$nextTick(() => {
        this.$refs.studentForm.init();
      });
    },
    editStudent(row) {
      this.studentVisible = true;
      this.studentTitle = "编辑学生";
      this.$nextTick(() => {
        this.$refs.studentForm.init(row);
      });
    },
    applyHandle(row) {
      this.applyVisible = true;
      this.applyWay = "single";
      this.$nextTick(() => {
        this.$refs.applyForm.init(row.user_id);
      });
    },
    deleteStudent(row) {
      this.$confirm("确定删除操作", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.tableDeleted("student", row.user_id);
        })
        .catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.u-btn-box {
  display: -webkit-box;
}
.u-btn {
  font-size: 12px;
  position: relative;
}
</style>
